package com.mju.controller;

import com.mju.controller.common.BaseController;
import com.mju.controller.common.JsonResult;
import com.mju.feign.clients.UserClient;
import com.mju.pojo.User;
import com.mju.service.IMailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestController
@RequestMapping("/email")
@Api(tags = "邮件服务")
public class MailController extends BaseController {

    @Autowired private IMailService mailService;
    @Autowired private UserClient userClient;

    /**
     * 生成激活链接
     * @param token
     * @param email
     * @return
     */
    @ApiOperation("生成激活邮件")
    @PostMapping("/generateActivationUrl")
    public JsonResult generateActivationUrl(
            @RequestParam("token") String token,@RequestParam("email") String email){
        // 生成激活链接
        log.info("正在生成激活链接...");
        String activationUrl = "http://localhost:10010/email/activation/" + token + "/0";
        log.info("激活链接"+activationUrl);
        this.sendMailForActivationAccount(activationUrl,email);
        return new JsonResult(OK);
    }

    /**
     * 发送激活邮件
     * @param activationUrl 激活链接
     * @param email 待激活用户的邮箱
     */
    @ApiOperation("发送激活邮件")
    @PostMapping("/sendMail")
    public JsonResult sendMailForActivationAccount(
            @RequestParam("activationUrl") String activationUrl, @RequestParam("email") String email){
        log.info("发送激活链接邮件...");
        mailService.sendMailForActivationAccount(activationUrl,email);
        return new JsonResult(OK,"发送激活链接邮件成功");
    }

  /**
   * 激活用户
   *
   * @param token 用户token
   * @param status 状态
   * @return
   */
  @GetMapping("/activation/{token}/{status}")
  @SneakyThrows
  public JsonResult activationAccont(
          @PathVariable String token, @PathVariable Integer status,
          HttpServletResponse response) {
        log.info("正在激活用户...");
        log.info("获取的参数为：token==>"+token+"status==>"+status);
         //解析token
//        token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIyNSIsImV4cCI6MTY4Njc1MDMzNn0.fwPnhJx9PzXOxhtwA6lMnWLLvqCFadVN6Xw_fVSqfkI";
        Integer uid = Integer.valueOf(parseTokenGetUid(token));
        JsonResult<User> data = userClient.getById(uid);
        User user = data.getData();
        JsonResult jsonResult = userClient.updateStatus(uid, status);

        response.sendRedirect("http://localhost:8090/activateEmail");

        return new  JsonResult(OK,"激活用户成功");
    }
}
